﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MebAppMarketplace.Biz
{
    public class UserAuthorizationHandler : AuthorizationHandler<UserAuthorizationRequirement>
    {
        
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserAuthorizationRequirement requirement)
        {
            if (!context.User.HasClaim(c => c.Type == ClaimTypes.Role &&
                                      c.Issuer == "http://contoso.com"))
            {
                return Task.CompletedTask;
            }
            var roles = context.User.FindFirst(x => x.Type == ClaimTypes.Role &&
                                      x.Issuer == "http://contoso.com").Value;
            if (roles.Split(',').Any(x => x == requirement.Role))
            {
                context.Succeed(requirement);
            }
            return Task.CompletedTask;
        }
    }

    public class UserAuthorizationRequirement : IAuthorizationRequirement
    {
        public string Role { get; set; }
        public UserAuthorizationRequirement(string role)
        {
            this.Role = role;
        }
    }
}
